import Vue from 'vue'
import VueRouter from 'vue-router'
// 二级路由
import Cart from '@/views/layout/cart'
import Category from '@/views/layout/category'
import Home from '@/views/layout/home'
import User from '@/views/layout/user'
import store from '@/store'
// 一级路由
import LayOut from '@/views/layout'
// 组件懒加载(异步组件-按需加载)
const Login = () => import('@/views/login')
const MyOrder = () => import('@/views/myorder')
const Pay = () => import('@/views/pay')
const ProDeatil = () => import('@/views/prodetail')
const SearchList = () => import('@/views/search/list')
const Search = () => import('@/views/search')

Vue.use(VueRouter)

// 但凡是单个页面,独立展示都是一级路由
const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: LayOut,
      directives: '/home',
      children: [
        { path: '/home', component: Home },
        { path: '/category', component: Category },
        { path: '/cart', component: Cart },
        { path: '/user', component: User }
      ]
    },
    { path: '/search', component: Search },
    { path: '/searchlist', component: SearchList },
    // 动态路由传参,确认将来时哪个商品,路由参数中携带id
    { path: '/prodetail/:id', component: ProDeatil },
    { path: '/pay', component: Pay },
    { path: '/myorder', component: MyOrder }
  ]
})

// 所有的路由在真正被访问到之前(解析渲染对应组件页面前),都会先经过全局前置导航守卫
// 只有全局前置守卫放行,才会到达对应的页面
// to:      到哪里去,到哪去的完整路由信息对象(路径,参数)
// from:    从哪里来,从哪来的完整路由信息对象(路径,参数)
// next():  是否放行
//  1)next()  直接放行,放行到to要去的路径
//  2)next(路径)  进行拦截,拦截到next里面配置的路径

// 定义数组,专门用户存放所有需要权限访问的页面
const authUrls = ['/pay', '/myorder']

router.beforeEach((to, from, next) => {
  // 看to.path是否在authUrls中出现过
  if (!authUrls.includes(to.path)) {
    // 非权限页面直接放行
    next()
    return
  }
  // 权限页面需要判断token
  const token = store.getters.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
